
#include "driver/i2c_master.h"
#include <stdio.h>
#include "driver/gpio.h"
#include "esp_err.h"
#include "esp_log.h"
#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

#define SC12B_ADDRESS 0x40
#define SC12B_Output1 0x08
#define SC12B_Output2 0x09

#define SC12B_INTTERUPT_PIN GPIO_NUM_3
static QueueHandle_t gpio_evt_queue = NULL;
esp_err_t bsp_i2c_init(void);

i2c_master_dev_handle_t i2c_dev_handle;
void IRAM_ATTR gpio_isr_handler(void* arg) {
    // 处理中断响应
    uint32_t gpio_num = (uint32_t) arg;
    xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
}


void receive_int_task(){
    uint32_t io_num;
    extern i2c_master_bus_handle_t bsp_i2c_bus;
    while(1){
        if(xQueueReceive(gpio_evt_queue, &io_num, pdMS_TO_TICKS(100))) {
            printf("GPIO[%"PRIu32"] intr, val: %d\n", io_num, gpio_get_level(io_num));
            uint8_t addr = SC12B_Output1;
            uint8_t read_buffer[2]={0};
            i2c_master_transmit_receive(i2c_dev_handle,&addr,1,read_buffer,2,1000);
            uint16_t current_state = read_buffer[0]<<4 |read_buffer[1]>>4;
            for(int i=0;i<12;i++){
                if( (1<<i&current_state)>0 ){
                    printf("key down:%d\r\n",i);
                }
            }
            //printf("%d  %d\r\n",read_buffer[0],read_buffer[1]);
        }
        vTaskDelay(pdMS_TO_TICKS(20));
    }
}


void example_SC12B_test_main(){
    //创建一个队列来处理来自isr的gpio事件
    gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));

    bsp_i2c_init();
    extern i2c_master_bus_handle_t bsp_i2c_bus;

     i2c_device_config_t i2c_dev_conf = {
        .scl_speed_hz = 400000,
        .device_address = SC12B_ADDRESS,
    };

    
    i2c_master_bus_add_device(bsp_i2c_bus, &i2c_dev_conf, &i2c_dev_handle);


    // 配置终端应交
    gpio_config_t interrupt_gpio_config = {
            .pin_bit_mask = BIT64(SC12B_INTTERUPT_PIN),          //配置引脚
            .mode =GPIO_MODE_INPUT,                  //输入模式
            .pull_up_en = GPIO_PULLUP_DISABLE,        //使能上拉
            .pull_down_en = GPIO_PULLDOWN_DISABLE,    //不使能下拉
            .intr_type = GPIO_INTR_POSEDGE|GPIO_INTR_NEGEDGE            //下降沿触发
    };
    // gpio参数配置
    gpio_config(&interrupt_gpio_config);

    // 安装 GPIO 中断服务程序
    gpio_install_isr_service(ESP_INTR_FLAG_EDGE);  
    
    uint32_t pin = SC12B_INTTERUPT_PIN;
    // 设置中断处理函数           
    gpio_isr_handler_add(SC12B_INTTERUPT_PIN, gpio_isr_handler, &pin);
    // 开启中断
    gpio_intr_enable(SC12B_INTTERUPT_PIN);

     // 启动串口接收线程
    xTaskCreate(receive_int_task, " PIN INTERUPT", 2048, NULL, 10, NULL);
}